package it.fuesi.expired;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import it.fuesi.expired.formbinders.AbstractFormBinder;
import it.fuesi.expired.formbinders.ItemFormBinder;
import it.fuesi.expired.formbinders.TagFormBinder;
import it.fuesi.expired.model.base.AModel;
import it.fuesi.expired.model.base.ErrorModel;


public class FormActivity extends Activity implements Button.OnClickListener {

    public static final int REQUEST_CODE = 201;
    public static final int REQUEST_CODE_IMAGE_CAPTURE = 301;


    public static final String EXTRA_CURRENT_FRG_POSITION = "CURR_FRG_POS";
    public static final String EXTRA_ID = "EXTRA_ID";

    private static final String TAG = "FormActivity";



    private Button mBtnSave;
    private Button mBtnCancel;
    private Button mBtnDelete;

    private AbstractFormBinder currentFormBinder;
    private int currentFormLayout;
    private String id;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        manageCurrentPosition(getIntent().getExtras());

        setContentView(currentFormLayout);

        mBtnSave = (Button)findViewById(R.id.btnSave);
        mBtnSave.setOnClickListener(this);

        mBtnDelete = (Button)findViewById(R.id.btnDelete);
        mBtnDelete.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteItem();
            }
        });


        mBtnCancel = (Button)findViewById(R.id.btnCancel);

        mBtnCancel.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                FormActivity.this.finish();
            }
        });

        currentFormBinder.onCreate(this);
    }

    @Override
    protected void onStart() {
        super.onStart();

        if(id != null){
            bindObject(id);
        }


    }

    public void takePicture(){
        final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_CODE_IMAGE_CAPTURE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        currentFormBinder.onActivityResult(requestCode, resultCode, data);
    }

    public static Intent makeIntent(Context ctx, int currentFragmentId) {
        final Intent intent = new Intent();
        intent.setClass(ctx, FormActivity.class);
        intent.putExtra(EXTRA_CURRENT_FRG_POSITION, currentFragmentId);
        return intent;
    }

    public static Intent makeIntent(Context ctx, int currentFragmentId, String id) {
        final Intent intent = makeIntent(ctx, currentFragmentId);
        intent.putExtra(EXTRA_ID, id);
        return intent;
    }

    private void manageCurrentPosition(Bundle bundle){
        int currentPosition = bundle.getInt(EXTRA_CURRENT_FRG_POSITION);
        if(currentPosition == MainActivity.FRG_POSITION_EXPIRED || currentPosition == MainActivity.FRG_POSITION_NOT_EXPIRED) {
            this.currentFormLayout =  R.layout.item_form;
            this.currentFormBinder = new ItemFormBinder();
        }else if(currentPosition == MainActivity.FRG_POSITION_TAGS) {
            this.currentFormLayout = R.layout.tag_form;
            this.currentFormBinder = new TagFormBinder();
        }

        if(bundle.containsKey(EXTRA_ID))
            id = bundle.getString(EXTRA_ID);
    }


    @Override
    public void onClick(View view) {
        //TODO: richiamato quando viene premuto il pulsante "Salva"

        final AModel obj = this.currentFormBinder.makeObject(FormActivity.this);
        obj.set_id(id);

        new SaveTask().execute(obj);

    }

    public void deleteItem() {
        //TODO: richiamato quando viene premuto il pulsante "Delete"



        new DeleteTask().execute(id);

    }

    private void bindObject(String id){
        new LoadTask().execute(id);
    }


    private class LoadTask extends AsyncTask<String, Void, AModel> {

        @Override
        protected AModel doInBackground(String... params) {
            try {

                final String id;
                if(params != null && params.length > 0)
                    id = params[0];
                else
                    id = null;

                return currentFormBinder.get(id);



            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(AModel obj) {

            Log.d(TAG, "OnPostExecute:" + obj);


            if(obj.isSuccess()){
                currentFormBinder.bindObject(FormActivity.this, obj);
            }

        }

    }

    private class SaveTask extends AsyncTask<AModel, Void, AModel> {

        @Override
        protected AModel doInBackground(AModel... params) {
            try {

                final AModel obj;
                if(params != null && params.length > 0)
                    obj = params[0];
                else
                    obj = null;


               return currentFormBinder.save(obj);



            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(AModel obj) {

            Log.d(TAG, "OnPostExecute:" + obj);


            if(obj.isSuccess()){
                FormActivity.this.setResult(RESULT_OK);
                FormActivity.this.finish();
            }

        }

    }

    private class DeleteTask extends AsyncTask<String, Void, ErrorModel> {

        @Override
        protected ErrorModel doInBackground(String... params) {
            try {

                final String id;
                if(params != null && params.length > 0)
                    id = params[0];
                else
                    id = null;


                return currentFormBinder.delete(id);



            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(ErrorModel obj) {

            Log.d(TAG, "OnPostExecute:" + obj);


            if(obj.isSuccess()){
                FormActivity.this.setResult(RESULT_OK);
                FormActivity.this.finish();
            }

        }

    }
}
